package com.atguigu.gmall.mq.consumer;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;

/**
 * @author 搭忆长安
 * @version 1.0
 * @date 2021年07月12日 20:10
 * @ClassName:ConsumerTest
 * @Description: TODO
 */
@Component
@Log4j2
public class ConsumerTest {
  @RabbitListener(queues = "java_queue")
  public void receive(Channel channel, Message message)throws Exception{
      //获取消息的属性消息
      MessageProperties messageProperties = message.getMessageProperties();
      long deliveryTag = messageProperties.getDeliveryTag();
      try{
          //获取消息的内容
          byte[] body = message.getBody();
          String msg = new String(body, "utf-8");
          System.out.println("收到的消息为:"+msg);
          //int i= 1/0;
          //消息的编号--offset偏移量--指针
          System.out.println("消息的编号为:" + deliveryTag);
          //确认消息
          channel.basicAck(deliveryTag,false);
      }catch (Exception e){
         log.info(JSONObject.toJSONString(message));
         log.error(e.getMessage());
      }finally {
          //拒绝消息: false的时候,消费了消息以后,直接将消息出列丢弃掉
          //拒绝消息: true的时候,消费了消息以后,将消息重新放回队列
          channel.basicReject(deliveryTag,true);
          //不重复消费消息
          if(messageProperties.getRedelivered()){
              //将消息进行记录--日志---数据库
              log.info(JSONObject.toJSONString(message));
              //拒绝消息
              channel.basicReject(deliveryTag,false);
              return;
          }
          //放回队列,重新消费一次
          channel.basicReject(deliveryTag, true);
      }
  }
}
